package com.zzyl.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

// 过滤报警的数据 任务类
@Component
public class AlertJob {
  @Autowired
  private AlertRuleMapper alertRuleMapper;
  @Autowired
  private RedisTemplate<String,String> redisTemplate;
  @Autowired
  private AlertRuleService alertRuleService;
    /**
     * 每分钟过滤一下报警的信息
     */
    @Scheduled(cron = "0 * * * * ?")
    public void alertDateFliter(){
        // 1. 获取所有的报警规则
        List<AlertRule>  alertRuleList = alertRuleMapper.selectByFunctionId(null, null, null);
        if(CollectionUtil.isEmpty(alertRuleList)){
            return;
        }
        // 2. 从redis中获取 所有的设备数据
        List<Object>  jsonStr = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA_KEY);
        if(CollectionUtil.isEmpty(jsonStr)){
            return;
        }
        // 3. 将获取到的设备数据格式化成想要的数据
        List<DeviceDataVo> deviceDataVoList = new ArrayList<>();
        jsonStr.forEach(json ->
            deviceDataVoList.addAll(JSONUtil.toList(json.toString(), DeviceDataVo.class))
        );
        // 4. 遍历 报警信息处理器进行处理
        deviceDataVoList.forEach(deviceDataVo ->
            alertRuleService.alertFilter(deviceDataVo)
        );

    }
}
